import { ElTable, ElTableColumn } from 'element-plus'
import { defineComponent, h, type VNode, type FunctionalComponent, HtmlHTMLAttributes, computed, toRefs } from 'vue'
import AutoComponents from './autoComponents'

export interface Props {
  data: Array
  column: Array
}

export default defineComponent({
  name: 'MTable',
  props: {
    data: Array,
    column: Array,
  },
  setup(props: Props, { slots, emit }) {
    const { column } = toRefs(props)

    const CustomComponent: FunctionalComponent = (co): VNode =>
      h(AutoComponents, {
        is: co.subassembly,
        modelValue: [co.prop],
        'onUpdate:modelValue': (value) => emit('update:modelValue', value),
        ...co.subOptions,
      })

    const customSlot = (singleCol) => {
      const cope = singleCol.prop
      return slots[cope] ? slots[cope]?.() : singleCol.subOptions ? CustomComponent(singleCol) : slots.default?.()
    }

    const columns: FunctionalComponent = column.value.map((singleCol) => {
      return h(
        ElTableColumn,
        { ...singleCol },
        {
          default: customSlot(singleCol),
        }
      )
    })

    return (): VNode | null => h(ElTable, { ...props }, { default: () => columns })
  },
})
